﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;
using Core.Attributes;

namespace Core
{
    public static class XmlConfigurator
    {
        public static void Configure(object root, XElement element)
        {
            var o = root.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var propertyInfo in o)
            {
                var attribute = propertyInfo.GetCustomAttribute<XPathAttribute>();

                if (attribute == null)
                    continue;

                var xelement = element.XPathSelectElement(attribute.XPath);

                if (xelement == null)
                {
                    if (attribute.Required)
                        throw new Exception();
                    continue;
                }

                var value = xelement.Value;

                object newValue = null;

                var type = propertyInfo.PropertyType;

                if (type == typeof(string))
                    newValue = (string)value;
                else
                {
                    newValue = Convert.ChangeType(value, type);
                }


                propertyInfo.SetValue(root, newValue);
            }
        }
    }
}
